#-*- coding:utf-8 -*-
'''
Created on 2012-7-11

@author: johnny
'''
import time
import vm_exceptions
from db import databases
from utils import pinger

NETCARD_DEFAULT = {
                   "vnet_type": "Virtio ParaVirtual",
                   "pg": "Virtual Machine Network 0",
                   "seq": 1
                   }

VHD_DEFAULT = {
               "vhd_type": "IDE",
               "baseimg": '',
               "del": "no",
               "createvhd": "yes",
               "is_diff": "no",
               "cache": "none",
               "boot_seq": 1,
               "true_size": 320.0,
               "persistence": "yes",
               "size": 41943040.0
               }

VM_DEFAULT = {
               'hostUuid': '',
               'description': '',
               'bootDevice': 'cdn',
               'storage_path': '',
               'storage_uuid': '',
               'usb_dev_list': [],
               'pci_id': '',
               'hd': [],
               'memoryAllocatedInMb': '1024',
               'numVcpusAllocated': '1',
               'netcardAllPara': [],
               'usbip': [],
               'cdrom': 'None',
               'autoStart': 'no',
               'localTime': 'yes'
               }


class VMBase(object):
    def __init__(self):
        self.cfg = None
        #Indicate weather the vm is created
        self.host = None
        self.storage = None
        self.settled = False
        self.exe = None
        self.query = None
    
        
    def set_default_img(self):
        if self.cfg['storage_path']:
            self.hard_drive['baseimg'] = (self.cfg['storage_path'] + "/" +
                                          self.cfg['description'] + "/" +
                                          self.cfg['description'] + ".img")
    
    def get_storage_path(self):
        if self.cfg['storage_path']:
            return self.cfg['storage_path']
        else:
            return None
    
    def get_vmUuid(self):
        if self.query is not None and self.cfg is not None:
            keyword = "description=\'" + self.cfg['description'] + "\'"
            return self.query.get_vmUuid(keyword)
    
    def get_baseimg(self):
        return self.hard_drive['baseimg']
    
    def set_cfg(self, key, value):
        if key in self.cfg.keys():
            self.cfg[key] = value
        else:
            print "Invalid key" 
            
    def isStarted(self, timeout=120): 
        current = time.time()
        start = time.time()
        endtime = current + timeout
        while current < endtime:
            self.ip = self.query.get_vm_ip(self.cfg['description'])
            if pinger.ping(self.ip):
                return time.time() - start
            current = time.time()
            time.sleep(5)
        
        raise vm_exceptions.StartUpException()
       
    def update_cfg(self, cfgs):
        self.params.update(cfgs)

class VMS(VMBase):
    def __init__(self, name):
        VMBase.__init__(self)
        self.cfg = VM_DEFAULT
        self.cfg['description'] = name
        self.hard_drive = VHD_DEFAULT
        self.netcard = NETCARD_DEFAULT
    
    def initialize(self, host, storage, executor):
        self.host = host
        self.storage = storage
        self.query = databases.DBQuery(host, user="postgres")
        self.exe = executor
        
    def start(self):
        params = {}
        params['parentUuid'] = self.cfg['hostUuid']
        params['vmUuid'] = self.get_vmUuid()
        params['storage_path'] = self.cfg['storage_path']
        
        self.exe.run(400, params, self.host)
        self.exe.wait_for_done(120)
    
    def poweroff(self):
        params = {}
        params['parentUuid'] = self.cfg['hostUuid']
        params['vmUuid'] = self.get_vmUuid()
        params['storage_path'] = self.cfg['storage_path']
        
        self.exe.run(401, params, self.host)
        self.exe.wait_for_done(120)
    
    def restart(self):
        params = {}
        params['parentUuid'] = self.cfg['hostUuid']
        params['vmUuid'] = self.get_vmUuid()
        params['storage_path'] = self.cfg['storage_path']
        
        self.exe.run(402, params, self.host)
        self.exe.wait_for_done(120)
    
    